import Vue from 'vue'
import { login, queryPermissionsByUser, logout, apiQueryCurrentUserInfo } from '@/api/system'
import { ACCESS_TOKEN, USER_NAME, USER_INFO } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { loadRoutes } from '@/utils/routerUtil'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login ({ commit }, param) {
      return new Promise((resolve, reject) => {
        login(param).then(response => {
          if (response.code === 1) {
            // const result = response.data
            // const userInfo = result.userInfo
            // Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
            // Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
            // Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            // commit('SET_TOKEN', result.token)
            // commit('SET_INFO', userInfo)
            // commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
            // commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          } else {
            throw new Error(response.data.errorMsg || '登录异常！')
          }
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetPermissionList ({ commit }) {
      return new Promise((resolve, reject) => {
        const vToken = Vue.ls.get(ACCESS_TOKEN)
        const params = { token: vToken }
        queryPermissionsByUser(params).then(res => {
          console.log('queryPermissionsByUser==>', res)
          loadRoutes(res.data)
          commit('SET_ROLES', res.data)
          apiQueryCurrentUserInfo().then(userInfoRes => {
            const userInfo = userInfoRes.data
            console.log(userInfo)
            commit('SET_NAME', { username: userInfo.loginName, realname: userInfo.userName, welcome: welcome() })
            Vue.ls.set(USER_NAME, userInfo.loginName, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            resolve(res)
          })
          /* const menuData = response.result.menu;
          const authData = response.result.auth;
          const allAuthData = response.result.allAuth;
          sessionStorage.setItem(USER_AUTH,JSON.stringify(authData));
          sessionStorage.setItem(SYS_BUTTON_AUTH,JSON.stringify(allAuthData));
          if (menuData && menuData.length > 0) {
            menuData.forEach((item) => {
              if (item["children"]) {
                let hasChildrenMenu = item["children"].filter((i) => {
                  return !i.hidden || i.hidden == false
                })
                if (hasChildrenMenu == null || hasChildrenMenu.length == 0) {
                  item["hidden"] = true
                }
              }
            })
            commit('SET_PERMISSIONLIST', menuData)
          } else {
            reject('getPermissionList: permissions must be a non-null array !')
          } */
        }).catch(error => {
          reject(error)
        })
      })
    },

    // // 获取用户信息
    // GetInfo ({ commit }) {
    //   return new Promise((resolve, reject) => {
    //     getInfo().then(response => {
    //       if (response.code !== 0) {
    //         throw new Error('查询用户信息出错')
    //       }
    //       const result = formatToAntUserInfoMap(response.data)
    //
    //       if (result.role && result.role.permissions.length > 0) {
    //         const role = result.role
    //         role.permissions = result.role.permissions
    //         role.permissions.map(per => {
    //           if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
    //             const action = per.actionEntitySet.map(action => { return action.action })
    //             per.actionList = action
    //           }
    //         })
    //         role.permissionList = role.permissions.map(permission => { return permission.permissionId })
    //         commit('SET_ROLES', result.role)
    //         commit('SET_INFO', result)
    //       } else {
    //         reject(new Error('getInfo: roles must be a non-null array !'))
    //       }
    //
    //       commit('SET_NAME', { name: result.name, welcome: welcome() })
    //       commit('SET_AVATAR', result.avatar)
    //
    //       resolve(response)
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
        }).catch(() => {
        }).finally(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          Vue.ls.clear()
          resolve()
        })
      })
    }

  }
}

// /**
//  * 将后台的用户信息格式化为 antd 的用户信息格式
//  * @param data
//  */
// const formatToAntUserInfoMap = data => {
//   const defualtAvatar = '/avatar2.jpg'
//   // antd 的用户信息格式
//   const userInfo = {
//     'id': '',
//     'name': '',
//     'username': '',
//     'password': '',
//     'avatar': defualtAvatar,
//     'status': 1,
//     'telephone': '',
//     'lastLoginIp': '',
//     'lastLoginTime': '',
//     'creatorId': '',
//     'createTime': '',
//     'merchantCode': '',
//     'deleted': 0,
//     'roleId': '',
//     'role': {}
//   }
//   userInfo.id = data.userId
//   userInfo.name = data.name
//   userInfo.username = data.username
//   userInfo.password = data.password
//   userInfo.avatar = data.avatar || defualtAvatar
//   userInfo.telephone = data.telephone
//   userInfo.lastLoginIp = data.lastLoginIp || ''
//   userInfo.lastLoginTime = data.lastLoginTime
//   userInfo.creatorId = data.createdBy
//   userInfo.createTime = data.createdTime
//   userInfo.roleId = data.roles ? data.roles[0].roleId : ''
//   userInfo.role = formatToAntRoleObjMap(data.roles)
//   return userInfo
// }
//
// /**
//  * 将后台的角色信息格式化为 antd 的角色信息格式
//  * @param data
//  */
// const formatToAntRoleObjMap = data => {
//   // antd 的角色格式
//   const roleObj = {
//     'id': '',
//     'name': '',
//     'describe': '',
//     'status': 1,
//     'creatorId': '',
//     'createTime': '',
//     'deleted': 0,
//     'permissions': []
//   }
//   data.forEach(item => {
//     roleObj.id = item.roleId
//     roleObj.name = item.roleName
//     roleObj.describe = ''
//     roleObj.creatorId = item.createdBy
//     roleObj.createTime = item.createdTime
//     roleObj.permissions = roleObj.permissions.concat(formatToAntPermissionMap(item.menus, item.roleId))
//   })
//   return roleObj
// }

// const formatToAntPermissionMap = (data, roleId) => {
//   // antd 的权限格式
//   const permissions = []
//   data.forEach(menu => {
//     const permission = {
//       'roleId': '',
//       'permissionId': '',
//       'permissionName': '',
//       'actions': '',
//       'actionEntitySet': [],
//       'actionList': '',
//       'dataAccess': ''
//     }
//     const actionEntitySet = []
//     menu.actions.forEach(action => {
//       const obj = {
//         'action': '',
//         'describe': '',
//         'defaultCheck': false
//       }
//       obj.action = action.action
//       obj.describe = action.authorityName
//       actionEntitySet.push(obj)
//     })
//     permission.roleId = roleId
//     permission.permissionId = menu.menuNameEn
//     permission.permissionName = menu.menuName
//     permission.actionEntitySet = actionEntitySet
//     permissions.push(permission)
//   })
//   return permissions
// }

export default user
